<?php

namespace WeForge\Queue;

use HttpClient\Aliyun\MessageNotificationService\Application as Mns;
use Illuminate\Container\Container;
use Illuminate\Contracts\Queue\Job as JobContract;
use Illuminate\Queue\Jobs\Job;

class MnsJob extends Job implements JobContract
{
    /**
     * The Aliyun MNS client instance.
     *
     * @var \HttpClient\Aliyun\MessageNotificationService\Application
     */
    protected $mns;

    /**
     * The job instance.
     *
     * @var array
     */
    protected $job;

    /**
     * Create a new job instance.
     *
     * @param \Illuminate\Container\Container $container
     * @param \HttpClient\Aliyun\MessageNotificationService\Application $mns
     * @param array $job
     * @param string $connectionName
     * @param string $queue
     */
    public function __construct(Container $container, Mns $mns, array $job, $connectionName, $queue)
    {
        $this->container = $container;
        $this->mns = $mns;
        $this->job = $job;
        $this->queue = $queue;
        $this->connectionName = $connectionName;
    }

    /**
     * Get the job identifier.
     *
     * @return string
     */
    public function getJobId()
    {
        return $this->job['MessageId'];
    }

    /**
     * Get the raw body of the job.
     *
     * @return string
     */
    public function getRawBody()
    {
        return base64_decode($this->job['MessageBody'], true);
    }

    /**
     * Get the number of times the job has been attempted.
     *
     * @return int
     */
    public function attempts()
    {
        return (int) $this->job['DequeueCount'];
    }

    /**
     * Delete the job from the queue.
     *
     * @return void
     */
    public function delete()
    {
        parent::delete();

        $this->mns->queue_message->delete($this->queue, $this->job['ReceiptHandle']);
    }

    /**
     * Release the job back into the queue.
     *
     * @param  int  $delay
     * @return void
     */
    public function release($delay = 0)
    {
        parent::release($delay);

        $this->mns->queue_message->changeVisibility($this->queue, $this->job['ReceiptHandle'], max(1, $delay));
    }
}
